
import 'package:flutter/cupertino.dart';
import 'package:myapp/constants.dart';
import 'package:myapp/repository/datas/auth_data.dart';
import 'package:myapp/utils/sp_utils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

import '../../repository/api.dart';

class AuthViewModel with ChangeNotifier{
  RegisterInfo registerInfo = RegisterInfo();
  LoginInfo loginInfo = LoginInfo();

  Future<bool> register() async {
    if(registerInfo.name !=null && registerInfo.password !=null && registerInfo.rePassword !=null
        && registerInfo.password == registerInfo.rePassword){

      if((registerInfo.password?.length ?? 0) >=6){
        dynamic result =  await Api.instance.register(name: registerInfo.name,
            password: registerInfo.password, rePassword: registerInfo.rePassword);
        if( result is bool){
          return result;
        }else{
          return true;
        }
      }
      showToast("密码长度必须大于6");
      return false;
    }
    showToast("输入不能为空或者密码必须一致");
    return false;
  }

  ///登录
  Future<bool> login() async {
    if(loginInfo.name !=null && loginInfo.password !=null){
        AuthData authData =  await Api.instance.login(name: loginInfo.name,password: loginInfo.password);
        if(authData.username !=null && authData.username?.isNotEmpty ==true){
          print("authData.username = ${authData.username}");
          //登录成功后将信息保存在本地，保存用户名
          SpUtils.saveString(Constants.SP_USER_NAME, authData.username ?? "");
          return true;
        }
    }
    showToast("登录失效");
    return false;
  }

  void setLoginInfo({String? username,String? password}){
    if (username !=null){
      loginInfo.name = username;
    }
    if (password !=null){
      loginInfo.password = password;
    }
  }
}


class RegisterInfo{
  String? name;
  String? password;
  String? rePassword;
}

class LoginInfo{
  String? name;
  String? password;
}